#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string>

void Usage(const std::string proc)
{
    std::cout << "Usage:\n\t" << proc << "serverip" << std::endl;
}
// serverip serverport
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }

    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
        return 1;
    // 客户端也需要bind，但会自动bind
    // 并且不推荐，也不应该bind固定port -->客户端存在诸多程序，bind固定port可能导致某些程序因为port冲突，导致程序起不来
    // 填充server网络信息
    struct sockaddr_in serverinfo;
    serverinfo.sin_family = AF_INET;
    serverinfo.sin_port = htons(serverport);
    serverinfo.sin_addr.s_addr = inet_addr(serverip.c_str());
    socklen_t serverinfo_len = sizeof(serverinfo);

    while (true)
    {
        std::string inbuffer;
        std::cout << "Please echo# ";
        std::getline(std::cin, inbuffer);
        size_t n = sendto(sockfd, inbuffer.c_str(), inbuffer.size(), 0, (struct sockaddr *)&serverinfo, serverinfo_len);
        if (n > 0) // 消息发送成功，开始接收响应
        {
            char buffer[1024];
            struct sockaddr_in temp;
            socklen_t len = sizeof(temp);
            ssize_t m = recvfrom(sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&temp, &len);
            if (m > 0)
            {
                buffer[m] = 0;
                std::cout << "Server echo# " << buffer << std::endl;
            }
            else
                break;
        }
        else
            break;
    }
    close(sockfd);
    return 0;
}